﻿<%@page contentType="text/html;charset=utf-8" pageEncoding="utf-8"%>
<%@page import="java.sql.*" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
<title>登录程序之验证页面</title>
</head>
<body>
<%!  
 String check(String userid, String userpwd){
	Connection conn = null;
	PreparedStatement pstmt = null;
	ResultSet rs = null;
	String uname = "";
	try{
		Class.forName("com.mysql.jdbc.Driver");
		String url = "jdbc:mysql://localhost:3306/db_news";
		String user = "root";
		String password = "root";
		conn = DriverManager.getConnection(url,user,password);

		String sql = "select * from user where userid=? and userpwd=?";
		pstmt = conn.prepareStatement(sql);	
		pstmt.setString(1, userid);
		pstmt.setString(2, userpwd);
		
		rs = pstmt.executeQuery();
		
		if(rs.next()){
			uname = rs.getString("username"); 
		}

	 }catch (ClassNotFoundException e) {
		 System.out.print(e.getMessage());

	 }catch (SQLException e) {
		 System.out.print(e.getMessage());
		 
	 }finally{
		if(rs != null){ 
			try{
			   	rs.close(); 
			}catch(SQLException e){
				System.out.print(e.getMessage());
			}
		}
		if(pstmt != null){ 
			try{
				pstmt.close(); 
			}catch(SQLException e){
				System.out.print(e.getMessage());
			} 
		}
		if(conn != null){ 
			try{
				conn.close(); 
			}catch(SQLException e){
				System.out.print(e.getMessage());
			} 
		}
		
		return uname;
	}
 }
%>
<%
	request.setCharacterEncoding("UTF-8");
	String id = request.getParameter("id");
	String password = request.getParameter("password");
	String remember = request.getParameter("remember");
	String name;
//	Cookie[] cookies;
	if((!(name=check(id,password)).equals(""))){  //登录成功，跳转到成功页
/*	   cookies = request.getCookies();
		int i;
		boolean cookies_flag = false; //表示是否创建Cookie
		if(cookies != null){
	   		for(i=0; i<cookies.length; i++){
	   			if("Cookie2019".equals(cookies[i].getName())){
	   				break;
	   			}
	   		}
	   		if(i<cookies.length){
	   			cookies_flag = false;
	   		}else{
	   			cookies_flag = true;
	   		}
	   	}else{
	   		cookies_flag = true;
	   	}
*/		
		Cookie cookie;
	   
		if(remember != null){
//	    	if(cookies_flag){
	    		cookie = new Cookie("Cookie2019", id+"#"+password);
	    		cookie.setMaxAge(10);
	    		response.addCookie(cookie);
//	    	}
	    }else{
//	    	if(!cookies_flag){
	    		cookie = new Cookie("Cookie2019", id+"#"+password);
	    		cookie.setMaxAge(0);
	    		response.addCookie(cookie);
//	    	}	    	
	    }
		
		session.setAttribute("username", name);
		session.setMaxInactiveInterval(60);
		response.sendRedirect("login_success.jsp");
		
	}else{              //登录失败，跳转到失败页
		   response.sendRedirect("login_failure.jsp");
	}
%>
</body>